const { exec } = require("../db/mysql")

// 获取博客列表
const getList = (author, keyword) => {
  // sql语句 1=1 类似于默认值 防止 author 与 keyword 不存在时造成的sql语句错误
  let sql = "select * from blogs where 1=1 "
  if (author) {
    sql += `and author="${author}" `
  }
  if (keyword) {
    // 包含 keyword 的博客
    sql += `and title like "%${keyword}%" `
  }
  // 降序排列
  sql += "order by createtime desc;"

  // 这里返回promise
  return exec(sql)
}

const getDetail = (id) => {
  const sql = `select * from blogs where id=${id};`
  return exec(sql).then((rows) => {
    return rows[0]
  })
}

const newBlog = (postData = {}) => {
  const { title, content } = postData.body
  const author = postData.session.username
  const createtime = Date.now()
  const sql = `
    insert into blogs (title,content,createtime,author)
    values ('${title}','${content}','${createtime}','${author}');`
  return exec(sql).then(resutl => {
    return { id: resutl.insertId }
  })
}

const updateBlog = (id, author, postData = {}) => {
  const { title, content } = postData
  const sql = `update blogs set title="${title}",content="${content}" where id="${id}" and author="${author}";`
  return exec(sql).then((updateCode) => {
    return affectedRows = updateCode.affectedRows
  })
}

const deleteBlog = (id, author) => {
  const sql = `delete from blogs where id="${id}" and author="${author}"`
  return exec(sql).then(delData => {
    return delCode = delData.affectedRows
  })
}
module.exports = {
  getList,
  getDetail,
  newBlog,
  updateBlog,
  deleteBlog
}